/**
 * 去除前后空白
 * @param {String} string
 */
export function trim(string) {
  return (string || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/, '')
}

/**
 * 检查元素是否存在类
 * @param {HTMLElement} el 目标元素
 * @param {String} cls 类名
 */
export function hasClass(el, cls) {
  if (!el || !cls) return false
  if (el.classList) {
    return el.classList.contains(cls)
  } else {
    return (' ' + el.className + ' ').indexOf(' ' + cls + ' ') > -1
  }
}

/**
 * 给元素添加类
 * @param {HTMLElement} el 目标元素
 * @param {String} cls 类名
 */
export function addClass(el, cls) {
  if (!el || !cls) return false
  let curClass = el.className
  let classes = (cls || '').split(' ')
  for (let index = 0; index < classes.length; index++) {
    let className = classes[index]
    if (!className) continue
    if (el.classList) {
      el.classList.add(className)
    } else if (!hasClass(el, className)) {
      curClass += ' ' + className
    }
  }
  if (!el.classList) {
    el.className = curClass
  }
}

/**
 * 去除元素类
 * @param {HTMLElement} el 目标元素
 * @param {String} cls 类名
 */
export function removeClass(el, cls) {
  if (!el || !cls) return false
  let curClass = el.className
  let classes = (cls || '').split(' ')
  for (let index = 0; index < classes.length; index++) {
    let className = classes[index]
    if (!className) continue
    if (el.classList) {
      el.classList.remove(className)
    } else if (hasClass(el, className)) {
      curClass = curClass.replace(' ' + className + ' ', '')
    }
  }
  if (!el.classList) {
    el.className = trim(curClass)
  }
}
